<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('活动成员列表')" />
    <style>
        /* 按钮禁用状态样式 */
        .btn.disabled, .btn:disabled {
            opacity: 0.65;
            cursor: not-allowed;
            pointer-events: all !important;
        }
        .btn:not(.disabled) {
            opacity: 1;
            cursor: pointer;
        }
        /* 表格行悬停和选中样式优化 */
        #bootstrap-table tbody tr {
            cursor: pointer; /* 鼠标悬停显示指针，提示可点击 */
        }
        #bootstrap-table tbody tr:hover {
            background-color: #f5f7fa; /* 悬停背景色 */
        }
        #bootstrap-table tbody tr.selected {
            background-color: #e4f0fd; /* 选中行背景色 */
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="member-form">
                <div class="select-list">
                    <ul>
                        <li>
                            活动名称：<input type="text" name="activityName"/>
                        </li>
                        <li>
                            成员姓名：<input type="text" name="memberName"/>
                        </li>
                        <li>
                            联系电话：<input type="text" name="phone"/>
                        </li>
                        <li>
                            报名状态：
                            <select name="joinStatus" th:with="type=${@dict.getType('join_status')}">
                                <option value="">所有</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                            </select>
                        </li>
                        <li>
                            活动状态：
                            <select name="status" th:with="type=${@dict.getType('activity_join_status')}">
                                <option value="">所有</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                            </select>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="system:member:add">
                <i class="fa fa-plus"></i> 新增
            </a>
            <a class="btn btn-primary" id="editBtn" onclick="$.operate.edit()" shiro:hasPermission="system:member:edit" disabled>
                <i class="fa fa-edit"></i> 修改
            </a>
            <a class="btn btn-danger" id="removeBtn" onclick="$.operate.removeAll()" shiro:hasPermission="system:member:remove" disabled>
                <i class="fa fa-remove"></i> 删除
            </a>
            <a class="btn btn-warning" id="exportBtn" onclick="$.table.exportExcel()" shiro:hasPermission="system:member:export" disabled>
                <i class="fa fa-download"></i> 导出
            </a>
            <a class="btn btn-info" onclick="$.table.refresh()"><i class="fa fa-refresh"></i> 刷新</a>
        </div>

        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<script th:inline="javascript">
    var prefix = ctx + "system/member";
    var joinStatusDatas = [[${@dict.getType('join_status')}]];
    var editFlag = [[${@permission.hasPermi('system:member:edit')}]];
    var removeFlag = [[${@permission.hasPermi('system:member:remove')}]];
    var exportFlag = [[${@permission.hasPermi('system:member:export')}]];

    $(function () {
        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            removeAllUrl: prefix + "/removeAll",
            exportUrl: prefix + "/export",
            modalName: "活动成员",
            columns: [
                {checkbox: true},
                {field: 'id', title: '编号', visible: true},
                {field: 'activityId', title: '活动ID', visible: true},
                {
                    field: 'activityName',
                    title: '活动名称',
                    formatter: function (value) {
                        return value || '-';
                    }
                },
                {field: 'eventDate', title: '活动日期', formatter: function (v) {
                        return v ? $.common.dateFormat(v, 'yyyy-MM-dd') : '-';
                    }},
                {field: 'memberName', title: '成员姓名'},
                {field: 'phone', title: '联系电话'},
                {field: 'email', title: '电子邮箱', visible: false},
                {field: 'createTime', title: '创建日期', formatter: function (v) {
                        return v ? $.common.dateFormat(v, 'yyyy-MM-dd HH:mm:ss') : '-';
                    }},
                {
                    field: 'joinStatus',
                    title: '报名状态',
                    formatter: function (value) {
                        var map = {
                            0: '<span class="label label-info">已报名</span>',
                            // 1: '<span class="label label-success">已成团</span>',
                            2: '<span class="label label-danger">已取消</span>',
                        };
                        return map[value] || '<span class="label label-warning">未知</span>';
                    }
                },
                {
                    field: 'status',
                    title: '活动状态',
                    formatter: function (value) {
                        var map = {
                            0: '<span class="label label-info">拼团中</span>',
                            1: '<span class="label label-success">已成团</span>',
                            2: '<span class="label label-danger">已取消</span>',
                            3: '<span class="label label-default">已结束</span>'
                        };
                        return map[value] || '<span class="label label-warning">未知</span>';
                    }
                },
                {field: 'remark', title: '备注', visible: false},
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row) {
                        var actions = [];
                        if (editFlag) {
                            actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        }

                        if (editFlag) {
                            if (String(row.joinStatus) === '0') {
                                actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="updateMemberStatus(\'' + row.activityId + '\', \'' + row.userId + '\', 2)"><i class="fa fa-times"></i>取消报名</a> ');
                                actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="updateMemberStatus(\'' + row.activityId + '\', \'' + row.userId + '\', 1)"><i class="fa fa-check"></i>确认成团</a>');
                            }
                            else if (String(row.joinStatus) === '2') {
                                actions.push('<a class="btn btn-primary btn-xs" href="javascript:void(0)" onclick="updateMemberStatus(\'' + row.activityId + '\', \'' + row.userId + '\', 0)"><i class="fa fa-undo"></i>恢复报名</a>');
                            }
                            else if (String(row.joinStatus) === '1') {
                                actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="updateMemberStatus(\'' + row.activityId + '\', \'' + row.userId + '\', 2)"><i class="fa fa-times"></i>取消报名</a>');
                            }
                        }

                        return actions.join('');
                    }
                }
            ],
            // 监听表格选择事件，动态更新按钮状态
            onCheck: function (row) {
                updateButtonStatus();
            },
            onUncheck: function (row) {
                updateButtonStatus();
            },
            onCheckAll: function (rows) {
                updateButtonStatus();
            },
            onUncheckAll: function (rows) {
                updateButtonStatus();
            },
            onLoadSuccess: function () {
                updateButtonStatus();
                // 初始化行点击事件（表格加载完成后绑定）
                bindRowClickEvent();
            }
        };
        $.table.init(options);
    });

    /**
     * 绑定表格行点击事件：点击任意单元格选中行并触发编辑
     */
    function bindRowClickEvent() {
        // 为表格 tbody 的所有行绑定点击事件
        $('#bootstrap-table tbody tr').on('click', function (e) {
            // 排除点击复选框和操作按钮时触发（避免冲突）
            if (!$(e.target).is(':checkbox') && !$(e.target).closest('.btn').length) {
                var $this = $(this);
                var $checkbox = $this.find('input[type="checkbox"]');

                // 切换选中状态（如果已选中则取消，未选中则选中）
                if ($checkbox.is(':checked')) {
                    $checkbox.prop('checked', false);
                    $.table("uncheck", $this.data('index')); // 同步表格选中状态
                } else {
                    // 先取消其他行选中状态
                    $('#bootstrap-table tbody tr').find('input[type="checkbox"]').prop('checked', false);
                    $.table("uncheckAll");

                    // 选中当前行
                    $checkbox.prop('checked', true);
                    $.table("check", $this.data('index')); // 同步表格选中状态
                }

                // 更新按钮状态
                updateButtonStatus();

                // 如果有编辑权限且仅选中一行，自动触发编辑弹窗
                var selectedRows = $.table.selectFirstColumns() || [];
                if (editFlag && selectedRows.length === 1) {
                    // 延迟50ms执行，确保选中状态同步完成
                    setTimeout(function() {
                        $.operate.edit(selectedRows[0]); // 传入选中行的ID
                    }, 50);
                }
            }
        });
    }

    /**
     * 更新按钮状态：未选择数据时禁用，选择后启用
     */
    function updateButtonStatus() {
        var selectedRows = $.table.selectFirstColumns() || [];
        var hasSelected = selectedRows.length > 0;
        var singleSelected = selectedRows.length === 1;

        $('#editBtn').prop('disabled', !editFlag || !hasSelected || !singleSelected);
        $('#removeBtn').prop('disabled', !removeFlag || !hasSelected);
        $('#exportBtn').prop('disabled', !exportFlag || !hasSelected);
    }

    /* 统一监听提交成功事件 */
    $(document).on('submitSuccess', function () {
        $.table.refresh();
        // 刷新后重新绑定行点击事件（避免分页或刷新后事件失效）
        setTimeout(bindRowClickEvent, 100);
    });

    /**
     * 更新成员状态
     */
    function updateMemberStatus(activityId, userId, status) {
        if (!editFlag) {
            $.modal.alertWarning("您没有修改活动成员的权限！");
            return;
        }

        var statusMap = {
            0: '恢复报名',
            1: '确认成团',
            2: '取消报名'
        };
        var statusName = statusMap[status] || '修改状态';

        $.modal.confirm("确定要" + statusName + "吗？", function () {
            var data = {
                activityId: activityId,
                userId: userId,
                joinStatus: status
            };
            $.operate.post(prefix + "/edit", data, function () {
                $.table.refresh();
                // 刷新后重新绑定事件
                setTimeout(bindRowClickEvent, 100);
            });
        });
    }
</script>
</body>
</html>
